<template>
  <t-dialog header="修改密码" :visible="props.show" @confirm="onSubmit" @close="closeUpdatePwd"
            :cancel-btn="authStore.isSimplePwd ? null : '取消'"
            :close-btn="!authStore.isSimplePwd"
            :close-on-esc-keydown="!authStore.isSimplePwd"
            :close-on-overlay-click="!authStore.isSimplePwd">
    <t-form ref="formRef" :data="formData" :rules="rules" @reset="closeUpdatePwd" @submit="onSubmit">
      <t-form-item label="原密码" name="oldPwd">
        <t-input v-model="formData.oldPwd" type="password"></t-input>
      </t-form-item>
      <t-form-item label="新密码" name="newPwd">
        <t-input v-model="formData.newPwd" type="password"></t-input>
      </t-form-item>
      <t-form-item label="确认密码" name="againPwd">
        <t-input v-model="formData.againPwd" type="password"></t-input>
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<script setup lang="ts">
import {type Ref, ref, unref} from "vue";
import {type FormValidateResult, MessagePlugin} from "tdesign-vue-next";
import {useRequest} from "vue-hooks-plus";
import {StrUtil} from "@/util/StrUtil.ts";
import {managerUpdatePwd} from "@/service/api/self.ts";
import {useAuthStore} from "@/store/modules/auth";
import type {UpdatePwdForm} from "@/typings/auth";
import type {Ret} from "@/typings/api";

const authStore = useAuthStore();

interface Props {
  show: boolean
}

const props = withDefaults(defineProps<Props>(), {
  show: false
})

const emit = defineEmits(['close'])

const formRef = ref();
const formData: Ref<UpdatePwdForm> = ref({
  oldPwd: '',
  newPwd: '',
  againPwd: ''
})

const rePassword = (val: string) => {
  return formData.value.newPwd === val;
}

const passwordValidator = (val: string) => {
  const regex = /^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/;
  return regex.test(val);
}

const rules = {
  oldPwd: [{required: true, message: '原密码必填', type: 'error'}],
  newPwd: [{required: true, message: '新密码必填', type: 'error'},
    {validator: passwordValidator, message: '密码必须为8位以上，且包含大小写字母、数字和特殊符号的字符串'},],
  againPwd: [
    // 自定义校验规则
    {required: true, message: '确认密码必填', type: 'error'},
    {validator: rePassword, message: '两次密码不一致'},
  ],
};


const updateRequest = useRequest<Ret<boolean>>(() => {
  const params = unref(formData);
  return managerUpdatePwd(params);
}, {
  manual: true,
  debounceWait: 500, //防抖
  onSuccess(res: Ret<boolean>) {
    if (res.success && res.data) {
      authStore.isSimplePwd = false;
      MessagePlugin.success('保存成功');
      closeUpdatePwd();
    } else {
      MessagePlugin.error(res.msg ?? "保存失败");
    }
  },
  onError(err) {
    MessagePlugin.error(err.message ?? "保存失败");
  }
});
const onSubmit = () => {
  if (formRef.value) {
    formRef.value.validate().then((res: FormValidateResult<FormData>) => {
      if (typeof res === "boolean") {
        updateRequest.run();
      }
    })
  }
};

const closeUpdatePwd = () => {
  if (formRef.value) {
    formRef.value.reset();
  }
  emit("close");
}
</script>

<style scoped lang="scss">

</style>